﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;


namespace AccessControl.Utility.BitmapUtility
{
	public class BitmapCreator
	{
		#region Constant
		[DllImport("gdi32.dll")]
		private static extern IntPtr CreateDIBitmap(IntPtr hdc, [In] ref BitmapInfoHeader lpbmih,
													uint fdwInit, byte[] lpbInit, byte[] lpbmi,
													uint fuUsage);
		/* constants for CreateDIBitmap */
		const int CBM_INIT = 0x04;   /* initialize bitmap */

		/* DIB color table identifiers */

		const int DIB_RGB_COLORS = 0; /* color table in RGBs */
		const int DIB_PAL_COLORS = 1; /* color table in palette indices */
		const int BI_RGB = 0;
		const int BI_RLE8 = 1;
		const int BI_RLE4 = 2;
		const int BI_BITFIELDS = 3;
		const int BI_JPEG = 4;
		const int BI_PNG = 5;
		#endregion

		#region Public Method

		public Bitmap CreateBitmap(IntPtr hdc, Size bmpSize, byte[] data)
		{
			var mem = new System.IO.MemoryStream();
			var bw = new System.IO.BinaryWriter(mem);
			//BITMAPINFO bmpInfo = new BITMAPINFO();
			var bmiHeader = new BitmapInfoHeader();
			bmiHeader.biSize = 40;
			bmiHeader.biWidth = bmpSize.Width;
			bmiHeader.biHeight = bmpSize.Height;
			bmiHeader.biPlanes = 1;
			bmiHeader.biBitCount = 8;
			bmiHeader.biCompression = BI_RGB;
			bw.Write(bmiHeader.biSize);
			bw.Write(bmiHeader.biWidth);
			bw.Write(bmiHeader.biHeight);
			bw.Write(bmiHeader.biPlanes);
			bw.Write(bmiHeader.biBitCount);
			bw.Write(bmiHeader.biCompression);
			bw.Write(bmiHeader.biSizeImage);
			bw.Write(bmiHeader.biXPelsPerMeter);
			bw.Write(bmiHeader.biYPelsPerMeter);
			bw.Write(bmiHeader.biClrUsed);
			bw.Write(bmiHeader.biClrImportant);

			for (int i = 0; i < 256; i++)
			{
				bw.Write((byte)i);
				bw.Write((byte)i);
				bw.Write((byte)i);
				bw.Write((byte)0);
			}


			var hBitmap = data != null ? CreateDIBitmap(hdc, ref bmiHeader, CBM_INIT, data, mem.ToArray(), DIB_RGB_COLORS) : CreateDIBitmap(hdc, ref bmiHeader, 0, null, mem.ToArray(), DIB_RGB_COLORS);
			return Image.FromHbitmap(hBitmap);
		}

		#endregion
	}
}
